﻿using BW.EatRabbit.Infrastructure.Interfaces;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BW.EatRabbit.Infrastructure.Implement
{
    /// <summary>
    /// 仓储实现层
    /// </summary>
    /// <typeparam name="T">实体</typeparam>
    public class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        /// <summary>
        /// 数据上下文
        /// </summary>
        private readonly DataDbContext _DB;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="DB">数据上下文</param>
        public BaseRepository(DataDbContext DB)
        {
            this._DB = DB;
        }
        /// <summary>
        /// 新增实体
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>返回受影响的行数</returns>
        public  int AddEntity(T entity)
        {
            _DB.Set<T>().Add(entity);
            return  _DB.SaveChanges();

        }
        
        /// <summary>
        /// 获取全部信息
        /// </summary>
        /// <returns>返回受影响的行数</returns>
        public IQueryable<T> GetAll()
        {
            return _DB.Set<T>().AsQueryable();
        }
        /// <summary>
        /// 根据ID获取实体
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns>返回实体</returns>
        public  T GetEntity(int id)
        {
            return  _DB.Set<T>().Find(id);
        }

        /// <summary>
        /// 更新实体
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>返回受影响的行数</returns>
        public  int UpdateEntity(T entity)
        {
            _DB.Set<T>().Update(entity);
            return  _DB.SaveChanges();
        }
        /// <summary>
        /// 批量修改
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>返回受影响的行数</returns>
        public int UpdateRange(IQueryable<T> entity)
        {
            _DB.Set<T>().UpdateRange(entity);
            return _DB.SaveChanges();
        }
    }
}
